package cn.sintang.core.list;

import cn.sintang.core.list.bean.User;

import java.util.*;

/**
 * 题目：List<User> user有参数id,userName,age,phone,idCard，如果userName和idCard一样表示是重复数据，过滤掉重复数据。
 * @author tangxy
 * @since 1.0
 * @date 2017-11-21
 */
public class ListRepeat {
    public static void main(String[] args) {
        List<User> users = new ArrayList<User>();
        User one = new User("1","小明",18,"123");
        User two = new User("2","小光",16,"110");
        User three = new User("3","小明",22,"123");
        User four = new User("4","小红",16,"998");
        User five = new User("5","小光",9,"119");
        User six = new User("6","小明",36,"123");
        users.add(one);
        users.add(two);
        users.add(three);
        users.add(four);
        users.add(five);
        users.add(six);
        // 双重for循环
        /// dealByDoubleForeach(users);
        // 使用hashSet
        dealBySet(users);
    }

    /**
     * 使用双层for循环
     * @param users
     */
    public static void dealByDoubleForeach(List<User> users){
        List<User> resultList = new ArrayList<User>();
        Map<String,String> resultMap = new HashMap<String,String>(16);
        for (User oneUser : users){
            // 判断是否已经存在于Map中
            boolean isRepeatId = resultMap.get(oneUser.getId())!=null ? true : false;
            if(isRepeatId){
                continue;
            }
            for (User twoUser : users){

                // id一样
                boolean isSampleId = oneUser.getId().equals(twoUser.getId());
                // 姓名和身份证一样
                boolean isSampleName = oneUser.getUserName().equals(twoUser.getUserName()) && oneUser.getIdCard().equals(twoUser.getIdCard());
                if(!isSampleId && isSampleName){
                    resultMap.put(twoUser.getId(),twoUser.getId());
                }
            }
            resultList.add(oneUser);
        }
        for (User user : resultList){
            System.out.println(user.toString());
        }
    }

    /**
     * 使用HashSet,重写User的hashCode和equals方法
     * @param users
     */
    public static void dealBySet(List<User> users){
        Set<User> userSet = new HashSet<User>(users);
        Iterator iterator = userSet.iterator();
        while(iterator.hasNext()){
            User user = (User) iterator.next();
            System.out.println(user.toString());
        }
    }
}
